import { RefObject } from 'react'
import { useIsomorphicLayoutEffect } from './use-isomorphic-layout-effect'
import { useMemoizedFn } from '@/library/hooks/use-memoized-fn'

export function useResizeEffect<E extends HTMLElement>(
  effect: (target: E) => void,
  targetRef: RefObject<E>,
): void {
  const fn = useMemoizedFn(effect)
  useIsomorphicLayoutEffect(() => {
    const target = targetRef.current
    if (!target) return
    if (window.ResizeObserver) {
      let animationFrame: number
      const observer = new ResizeObserver(() => {
        animationFrame = window.requestAnimationFrame(() => fn(target))
      })
      observer.observe(target)
      return () => {
        window.cancelAnimationFrame(animationFrame)
        observer.disconnect()
      }
    }
    fn(target)
  }, [targetRef])
}
